import os
import sys
import django

base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(base_dir)
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "s25.settings")
django.setup()
from django.conf import settings
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
import pika
# 1、连接rabbitmq服务器
from django.core.mail import send_mail

connection = pika.BlockingConnection(pika.ConnectionParameters(host=settings.SERVER_IP))
channel = connection.channel()

channel.queue_declare(queue='hello')


# 构建回调函数
def callback(ch, method, properties, list_str):
    """str=[email,username,user_id]"""
    list_str = list_str.decode('utf8')
    list = eval(list_str)
    email, username, user_id = list[0], list[1], list[2]
    print('MQ收到'+ list_str)
    subject = 'Saas项目追踪&管理平台 注册'
    message = ''
    sender = settings.EMAIL_FROM
    receiver = [email, ]
    serializer = Serializer(settings.SECRET_KEY)
    info = {'confirm': user_id}
    token = serializer.dumps(info)  # 加密是加密的这个字典，之后解码成utf8，就没有b'....'了，更好看一点
    token = token.decode()
    html_message = '<h1>尊敬的新用户{0}，欢迎您注册Saas平台</h1>请点击下面链接激活您的账户<br/><a href="http://www.lanyuechuan.xyz/user/active/{1}">http://www.lanyuechuan.xyz/user/active/{2}</a>'.format(
        username, token, token)
    # send_mail是django内置的发邮件函数，前四个是必须参数，实际项目中可以加上html_message
    send_mail(subject, message, sender, receiver, html_message=html_message)
    print('向目的邮箱{}发送邮件成功'.format(email))

    # 发送应答信号，表明数据已经处理完成，可以删除,和auto_ack=False套起来用
    ch.basic_ack(delivery_tag=method.delivery_tag)


# 确定监听队列：hello，一旦有值出现，则触发回调函数：callback
channel.basic_consume(queue='hello',
                      auto_ack=False,
                      on_message_callback=callback,
                      )

print('当前MQ简单模式正在等待生产者往消息队列塞消息.......要退出请按 CTRL+C.......')
channel.start_consuming()
